const bcrypt = require('bcryptjs')
const { getUserInfo } = require('../service/user.service')
const { 
    userFormateError, 
    userAlreadyExited, 
    userRegisterError, 
    userDoesNotExited, 
    userLoginError,
    invalidPassword
} = require('../constants/err.type')

const userValidator = async(ctx, next) => {
    const { user_name, password } = ctx.request.body

    if(!user_name.trim() || !password.trim()){
        console.error('用户名或密码为空', ctx.request.body)
        ctx.app.emit("error", userFormateError, ctx)
        return
    }

    await next()
}

const verifyUser = async(ctx, next) => {
    const { user_name } = ctx.request.body

    try{
        if(await getUserInfo({user_name})){
            console.error('用户已存在', ctx.request.body)
            ctx.app.emit("error", userAlreadyExited, ctx)
            return
        }
    }catch(err){
        console.error("用户注册失败", err)
        ctx.app.emit("error", userRegisterError, ctx)
        return
    }

    await next()
}

//密码加密
 const cryptPassword = async(ctx, next) => {
    const { password } = ctx.request.body

    const salt = bcrypt.genSaltSync(10)
    const hash = bcrypt.hashSync(password, salt)

    ctx.request.body.password = hash
    await next()
}

const verifyLogin = async(ctx, next) => {
    const { user_name, password } = ctx.request.body
    try{
        const res = await getUserInfo({user_name})
        // ctx.res = res
        if(!res){
            ctx.app.emit('error', userDoesNotExited, ctx)
            return
        }else{
            if(!bcrypt.compareSync(password, res.password)){
                ctx.app.emit('error', invalidPassword, ctx)
                return
            }
        }
    }catch(err){
        console.error("用户登录失败", err)
        ctx.app.emit('error', userLoginError, ctx)
        return
    }
    await next()
}

module.exports = {
    userValidator,
    verifyUser,
    cryptPassword,
    verifyLogin
}